import { observable, action, toJS, computed } from 'mobx';
import { Base64 } from 'js-base64';
import { Tools, Toast, Modal, Bubble } from 'weaver-mobile';
import { Browser } from 'weaver-mobile-page';
import * as API from '../../api/goal/goalBase'
import GoalCommonStore from './GoalCommonStore';
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const goalCommonStore = new GoalCommonStore()
export default class GoalMainStore {

  @observable sortcond = 3;//视图分类 1-列表 3-分类 4-层级
  @observable condtype = 1; //菜单分类 1-我的目标
  @observable loading = false; // 页面初始化的loading状态：数据加载成功前后前使用
  @observable dataBacklist = []; //后台返回的列表数据集合
  @observable datalist = []; //移动端实际使用的数据
  @observable datetype = [];//分类视图类型数组
  @observable swipelist = [];//左滑按钮的数组
  @observable isCompanyPerson = false; // 是否为公司目标负责人
  @observable hasmore = "";//列表模式下是否有更多
  @observable principaler = {}; //当前目标的负责人
  @observable addname = ""; //列表模式下快速创建文本框的value
  @observable isShowLevel = false // 是否展示层级视图
  @observable personCanCreate = false; //
  /**
   * 联动组件条件
   */
  @observable nowyear = "";//当前年
  @observable nowmonth = "";//当前月
  @observable nowseason = "";  //当前季度
  @observable currentperiod = "3";//当前周期 3-年度
  @observable currentstatus = "1";//当前状态 1-进行中
  /**
   * 高级搜索条件
   */
  @observable searchname = "";//搜索框 任务名称
  @observable orderby = "";//排序字段
  @observable orderbytype = "desc";//排序方式
  @observable principalid = [];//责任人
  @observable enddate = "";//结束时间
  @observable enddate1 = "";//结束时间
  @observable refreshDetail = false;//用于刷新详细
  @observable isShowType = true; // 用于判断分类列表是否展示数据
  @observable principaler = [];
  @observable tagArray = []; //标签数据
  @observable tag = ""; //标签搜索

  @observable refreshList = true;

  pagenum = 1;//列表模式当前页
  itotal = 1;//列表模式总条数
  pagesize = 20; //列表每页页数
  localtime = new Date().getTime();
  excludeids = "";//新增加的目标id

  //组织目标
  @observable canCreate = false;// 是否有创建权限
  @observable orgCardList = []; //组织卡片
  @observable currentOrgId = "0";//当前组织选项
  @observable typeId = ""; //目标类型 1公司目标 2分部目标 3部门目标
  @observable orgId = ""; //组织id
  @observable orgtitle = "";//标题

  @action
  setCanCreate = (data) => {
    this.canCreate = data;
  }

  @action
  setCondType = (data) => {
    this.condtype = data;
  }

  @action
  setTypeId = (data) => {
    this.typeId = data;
  }

  @action
  setOrgId = (data) => {
    this.orgId = data;
  }

  @action
  setOrgtitle = (data) => {
    this.orgtitle = data;
  }

  @action
  setCurrentOrgId = (data) => {
    this.currentOrgId = data;
  }

  @action
  setOrgData = (condtype, typeId, orgId, currentOrgId, orgtitle) => {
    this.condtype = condtype;
    this.typeId = typeId;
    this.orgId = orgId;
    this.currentOrgId = currentOrgId;
    this.orgtitle = orgtitle;
  }

  /**
   * 获取列表数据
   */
  @action
  goalListAll = (params) => {
    this.loading = true;
    this.getCommonParams(params)
    this.principaler = [];
    // this.dataBacklist = [];
    // this.datalist = [];
    this.changeShowBatchChoose(false)
    API.goalListAll(params).then(action(res => {
      if (res.status) {
        if (this.sortcond == 1) {
          this.hasmore = res.hasmore;
          this.itotal = res.total;
          this.pagenum = 1;
        }
        this.isCompanyPerson = res.isCompanyPerson;
        this.dataBacklist = res.datas;
        this.datetype = res.datetype;
        this.personCanCreate = res.canCreate;
        this.principaler.push(res.principaler);
        this.initGoalListDatas();
        if (typeof params.doback == "function") {
          params.doback();
        }
      } else {
        // message.error(res.msg || getLabel('25009','失败'));
      }
      this.loading = false;
    }));
  }

  /**
   * 加载更多
   */
  @action
  getMoreData = (params) => {
    this.loading = true;
    this.getCommonParams(params);
    params.excludeids = this.excludeids;
    API.getMore(params).then(action(res => {
      if (res.status) {
        if (this.sortcond == 1) {
          this.pagenum = params.pagenum;
          this.hasmore = res.hasmore;
        } else {
          if (this.datetype.length > 0) {
            this.datetype[params.index].isopen = true;
            this.datetype[params.index].pagenum = params.pagenum;
            this.datetype[params.index].hasmore = res.hasmore;
          }
        }
        this.dataBacklist = this.dataBacklist.concat(res.datas);
        this.initGoalListDatas();
      } else {
        // message.error(res.msg || getLabel('25009','失败'));
      }
      this.loading = false;
    }));
  }

  @action("获取组织卡片")
  goalCard = (params) => {
    this.loading = true;
    this.orgCardList = [];
    this.currentOrgId = "0"
    API.goalCard(params).then(action(res => {
      if (res.status) {
        this.orgCardList = res.list;
        // this.principaler = res.principaler;
        if (res.list.length > 0) {
          this.initOrgGoal();
        }
        if (typeof params.doback === "function") {
          if(res.list){
            params.doback(res.list.length);
          }else{
            params.doback();
          }
        }
      } else if (!res.api_status) {
        // message.error(res.msg || getLabel('25009','失败'));
      }
      this.loading = false;
    }));
  }

  @action
  initOrgGoal = () => {
    if (this.orgCardList && this.orgCardList.length > 0) {
      this.setOrgtitle(this.orgCardList[this.currentOrgId].orgName)
      this.setTypeId(this.orgCardList[this.currentOrgId].type)
      this.setOrgId(this.orgCardList[this.currentOrgId].orgId)
      this.setCanCreate(this.orgCardList[this.currentOrgId].canCreate)
    }
  }

  @computed
  get orgTypeList() {
    // let res = [{
    //     key: 'orgType',
    //     label: getLabel(376,'组织'),
    //     options:[],
    // }];
    let res = [];
    if (this.orgCardList.length > 0) {
      this.orgCardList.map((d, i) => {
        res.push({
          value: "" + i,
          label: d.orgName,
        })
      });
    } else {
      res = [];
    }
    return res;
  }

  @action
  setGoalBackendDatas = (datas) => {
    this.dataBacklist = datas;
  }

  /**
   * 格式化返回的数据，转化为移动端的数据格式
   */
  @action
  initGoalListDatas = () => {
    let datas = []
    this.dataBacklist.forEach((d, i) => {
      datas.push(this.formatBackendData(d))
    })
    this.datalist = datas
  }


  @observable
  showBatchChoose = false

  @action
  changeShowBatchChoose = (value) => {
    this.showBatchChoose = value
  }

  @observable
  isBatchChoosed = false

  @action
  changeIsBatchChoosed = (val) => {
    this.isBatchChoosed = val
  }

  @action
  clearBatchInfo = () => {
    this.changeIsBatchChoosed(false)
    this.batchChoose(false)
    this.changeShowBatchChoose(false)
  }

  @computed
  get batchChooseNum() {
    return this.datalist.filter((d, i) => d.checked).length
  }

  @action
  batchChoose = (choose = true) => {
    this.datalist.forEach((d, i) => {
      d.checked = choose
    })
  }

  @action
  onGoalCheckedChange = (goalid, checked) => {
    this.datalist.forEach((d, i) => {
      if (d.id == goalid) {
        d.checked = checked
      }
    })
  }

  @action
  batchSetTagOperation = (params) => {
    const { tagtype } = params
    if (tagtype == "3") {  // 清除标签
      Modal.alert(getLabel('386786', '信息确认'), params.infos, [
        { text: getLabel(201, '取消'), style: 'default' },
        {
          text: getLabel('826', '确定'),
          onPress: () => {
            this.doBatchSetTag(params)
          }
        }
      ])
    } else {
      this.doBatchSetTag(params)
    }
  }

  @action
  doBatchSetTag = (params) => {
    const { tagids, tagtype, opentagtype, doback } = params
    this.loading = true;
    API.editGoalField({
      fieldname: "tag",
      opentagtype,
      tagtype,
      goalids: "," + this.datalist.filter((d, i) => d.checked).map((d, i) => d.id).join(","),
      fieldvalue: tagids
    }).then(res => {
      if (res.status == "1") {
        if (tagtype == "3") {
          this.datalist.forEach((goal, ti) => {
            if (goal.checked) {
              goal.tags = []
            }
          })
        } else {
          if (res.goalTagMap) {
            for (let k in res.goalTagMap) {
              this.datalist.forEach((goal, ti) => {
                if (goal.id == k) {
                  goal.tags = res.goalTagMap[k] || []
                }
              })
            }
          }
        }
      }
      this.datalist = [...this.datalist]
      this.clearBatchInfo()
      this.loading = false;
      typeof doback === "function" && doback(res)
    })
  }


  /**
   * 格式化返回的数据方法
   */
  @action
  formatBackendData = (d) => {
    let date = new RegExp(/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/).test(d.rightData[1].name) ? d.rightData[1].name : ""
    let commentCount = 0
    if (d.rightData.length == 2 && date == "") {
      commentCount = parseInt(d.rightData[1].name.substring(1, d.rightData[1].name.length - 1))
    }
    if (d.rightData.length == 3) {
      commentCount = parseInt(d.rightData[2].name.substring(1, d.rightData[2].name.length - 1))
    }
    return {
      ...d,
      id: d.key,
      originalData: d,
      firstview: d.firstview,
      treetype: d.treetype,
      title: d.title,
      user: d.rightData[0].name,
      date: date,
      commentCount: commentCount,
      comsbtn: d.comsbtn.filter((btn, i) => {
        return btn.type != "tag"
      }).reverse().map((btn, i) => {
        return {
          text: btn.com,
          onPress: () => { this.getSwipeBtnCallback(btn.type)(d.key, btn.type) },
          style: { backgroundColor: this.getSwipeBtnBgcolor(btn.type), color: 'white', padding: "0 15*@hd", maxWidth: "75*@hd", minWidth: "40*@hd", }
        }
      }),
      hasChildren: d.childcount && parseInt(d.childcount + "") > 0,
      childrenOpen: false,
      checked: false
    }
  }


  /**
   * 滑动按钮的回调函数
   */
  getSwipeBtnCallback = (btntype) => {
    if (btntype == "complete" || btntype == "progress" || btntype == "redo") {
      return this.onGoalChangeStatus
    } else if (btntype == "special" || btntype == "canclespecial") {
      return this.onGoalMarkAttention
    } else if (btntype == "addfb") {
      return this.onGoalAddFb
    } else if (btntype == "delete") {
      return this.onGoalDelete
    } else {
      return () => {
        console.log("can`t revolve this btntype")
      }
    }
  }

  /**
   * 删除
   */
  onGoalDelete = (id, btntype) => {
    Modal.alert(getLabel(131329, '信息确认'), getLabel(127574, '确定删除吗？'), [
      {
        text: getLabel(31129, '取消'),
        style: 'default'
      }, {
        text: getLabel(33703, '确认'),
        onPress: () => {
          this.loading = true;
          API.editStatus({
            goalId: id,
            status: "4"
          }).then(res => {
            if (res && res.status) {
              Bubble.success(getLabel(31439, '更新成功'), 1);
              this.dataBacklist.filter((d, i, arr) => {
                if (d.key == id) {
                  arr.splice(i, 1)
                }
              })
              this.initGoalListDatas()
            } else {
              Bubble.error(getLabel('25009', '失败'), 1)
            }
            this.loading = false;
          })
        }
      }
    ])
  }

  /**
   * 状态改变更改函数
   */
  onGoalChangeStatus = (id, btntype) => {
    Modal.alert(getLabel(131329, '信息确认'), btntype == "complete" ? getLabel(508754, '确认标记完成吗') : getLabel(508755, '确认标记进行吗'), [
      {
        text: getLabel(31129, '取消'),
        style: 'default'
      },
      {
        text: getLabel(33703, '确认'),
        onPress: () => {
          this.loading = true;
          API.editStatus({
            goalId: id,
            status: btntype == "complete" ? "2" : "1"
          }).then(res => {
            if (res && res.status) {
              Bubble.success(getLabel(31439, '更新成功'), 1);
              let newDataBackendDatas = []
              this.dataBacklist.forEach((d, i) => {
                if (d.key == id) {
                  d.status = btntype == "complete" ? "2" : "1"
                  // d.iconclass = btntype == "redo" ? "progress" : btntype;
                  // d.iconcolor = this.getSwipeBtnBgcolor(btntype)
                  d.comsbtn.forEach((btn, i) => {
                    if (btn.type == "complete" || btn.type == "redo" || btn.type == "progress") {
                      btn.type = btn.type == "complete" ? "progress" : "complete";
                      btn.com = btn.com == getLabel(382564, '标记完成') ? getLabel(382565, '标记进行') : getLabel(382564, '标记完成');
                    }
                  })
                  // if(toJS(d.comsbtn).length == 3){
                  //   d.comsbtn[2].com = d.comsbtn[2].com == getLabel(382564,'标记完成')? getLabel(382565,'标记进行') :getLabel(382564,'标记完成');
                  //   d.comsbtn[2].type = btntype == "complete" ? "progress" : "complete";
                  // }
                }
                newDataBackendDatas.push(d)
              })
              this.setGoalBackendDatas(newDataBackendDatas)
              this.initGoalListDatas()
            } else {
              Bubble.error(getLabel('25009', '失败'), 1)
            }
            this.loading = false;
          })
        }
      }
    ])
  }

  /**
   * 关注状态
   */
  onGoalMarkAttention = (id, btntype) => {
    this.loading = true;
    API.setSpecial({
      goalId: id,
      special: btntype == "special" ? "1" : "0"
    }).then(res => {
      if (res && res.status) {
        Bubble.success(getLabel(31439, '更新成功'), 1);
        let newDataBackendDatas = []
        this.dataBacklist.forEach((d, i) => {
          if (d.key == id) {
            d.comsbtn.forEach((btn, i) => {
              if (btn.type == "special" || btn.type == "canclespecial") {
                btn.type = btn.type == "special" ? "canclespecial" : "special";
                btn.com = btn.com == getLabel(25436, '关注') ? getLabel(26938, '取消关注') : getLabel(25436, '关注');
              }
            })
            // if(d.comsbtn.length == 3){
            //     d.comsbtn[1].com = d.comsbtn[1].com == getLabel(25436,'关注')  ? getLabel(26938,'取消关注') :getLabel(25436,'关注') ;
            //     d.comsbtn[1].type = btntype == "special" ? "canclespecial" : "special";
            // }
          }
          newDataBackendDatas.push(d)
        })
        this.setGoalBackendDatas(newDataBackendDatas);
        this.initGoalListDatas();
      } else {
        Bubble.error(getLabel('25009', '失败'), 1)
      }
      this.loading = false;
    })

  }

  getDataByRecursion = (targetDatas, targetDataId, res = {}) => {
    if (targetDatas && targetDatas.length > 0) {
      for (let i = 0; i < targetDatas.length; i++) {
        if (targetDatas[i].id == targetDataId) {
          res.data = targetDatas[i]
          res.belongArr = targetDatas
        }
        this.getDataByRecursion(targetDatas[i].children, targetDataId, res)
      }
    }
    return res
  }

  //监听此对象发生改变时自动跳转到详情反馈页
  @observable
  jumpGoalFbMonitor = {}

  @action
  changeJumpTaskMonitor = (jumpGoalFbMonitor) => {
    this.jumpGoalFbMonitor = jumpGoalFbMonitor
  }

  /**
   * 添加反馈
   */
  onGoalAddFb = (id, btntype) => {
    this.changeJumpTaskMonitor({
      id
    })
  }

  /**
   * 滑动按钮的颜色
   */
  getSwipeBtnBgcolor = (btntype) => {
    if (btntype == "complete" || btntype == "progress" || btntype == "redo") {
      return "rgba(77, 122, 216, 1)"
    } else if (btntype == "special" || btntype == "canclespecial") {
      return "rgba(245, 154, 35, 1)"
    } else if (btntype == "addfb") {
      return "rgba(170, 170, 170, 1)"
    } else if (btntype == "delete") {
      return "rgb(51, 51, 51)"
    } else {
      return ""
    }
  }


  /**
   * 获取请求参数
   */
  @action
  getCommonParams = (params) => {
    params.sorttype = this.sortcond;
    params.condtype = this.condtype;
    params.period = this.currentperiod;
    params.status = this.currentstatus;
    params.periody = this.nowyear;
    params.periodm = this.nowmonth;
    params.periods = this.nowseason;
    params.pagesize = this.sortcond == 1 ? 10 : 5;
    params.searchname = this.searchname;
    params.orderby = this.orderby;
    params.orderbytype = this.orderbytype;
    params.typeId = this.typeId;
    params.orgId = this.orgId;
    if (this.principalid && this.principalid.length > 0) {
      params.principalid = this.principalid[0].id;
    }
    if (this.tagArray && this.tagArray.length > 0) {
      params.tag = this.tagArray[0].id;
    }
    params.enddate = this.enddate;
    params.enddate1 = this.enddate1;
  }

  /**
   * 设置请求参数
   */
  @action
  setCommonParams = (params, type, advanceSearch) => {
    if (params && params != "") {
      if (params.currentOrgId) {
        this.currentOrgId = params.currentOrgId;
        this.initOrgGoal();
      }
      this.currentperiod = params.period;
      this.currentstatus = params.status;
      this.nowyear = params.year;
      this.nowmonth = params.month;
      this.nowseason = params.quarter;
      this.resetDataList();
    }
    if (type && type != "") {
      this.sortcond = type;
    }
    if (type != "" && type != 4) { //切换视图时 判断是否为分类和列表视图需要刷新
      this.resetDataList();
    }
    if (advanceSearch && advanceSearch != "") {
      this.searchname = advanceSearch.goalName;
      this.principalid = advanceSearch.principal
      this.enddate = advanceSearch.endDate
      this.enddate1 = advanceSearch.endDateT
      this.orderby = advanceSearch.orderby
      this.orderbytype = advanceSearch.orderbytype
      this.tagArray = advanceSearch.tagArray;
    }
    this.setIsShowLevel("", type)
  }

  @computed
  get condTypeOptions() {
    return [
      {
        key: "1",
        path: "1",
        menuname: getLabel(18028, "我的目标")
      },
      {
        key: "3",
        path: "3",
        menuname: getLabel(506156, "我创建的目标")
      },
      {
        key: "4",
        path: "4",
        menuname: getLabel(506157, "我参与的目标")
      },
      {
        key: "6",
        path: "6",
        menuname: getLabel(506158, "我关注的目标")
      },
      {
        key: "5",
        path: "5",
        menuname: getLabel(506159, "分享给我的目标")
      },
      {
        key: "0",
        path: "0",
        menuname: getLabel(506160, "所有目标")
      },
      {
        key: "2",
        path: "2",
        menuname: getLabel(518141, "组织目标")
      },
      {
        key: "8",
        path: "8",
        menuname: getLabel(519221, '我创建的组织目标')
      },
      {
        key: "9",
        path: "9",
        menuname: getLabel(518775, '分享给我的组织目标')
      },
    ]
  }



  /**
   * 切换目标
   */
  @action
  changeCondType = (condtype,isRefresh = true) => {
    if (condtype == 2) {
      this.sortcond == 4;
    }
    if (this.sortcond == 4 && condtype != 2) {
      this.sortcond = 3;
    }
    this.condtype = condtype;
    this.setIsShowLevel(condtype)
    isRefresh && this.resetDataList();
  }

  /**
   * 设置是否展示层级视图
   */
  @action
  setIsShowLevel = (condtype, sortcond) => {
    if (condtype == 2 || sortcond == 4) {
      this.isShowLevel = true;
    } else {
      this.isShowLevel = false;
    }
  }

  /**
   * 重置数据
   */
  @action
  resetDataList = () => {
    this.datalist = [];
    this.datetype = [];
    this.dataBacklist = [];
    this.isCompanyPerson = false;
    this.goalListAll({});
  }

  @action
  setSearchname = (v) => {
    this.searchname = v;
  }

  @action
  setSortCond = (v) => {
    this.sortcond = v
  }

  @action
  resetSearchData = () => {
    this.searchname = ""
    this.orderby = ""
    this.orderbytype = "desc"
    this.principalid = []
    this.enddate = "";
    this.enddate1 = "";
  }

  @observable
  advancedSearchPopoverVisible = false

  @action
  changeAdvancedSearchPopoverVisible = (advancedSearchPopoverVisible) => {
    this.advancedSearchPopoverVisible = advancedSearchPopoverVisible
  }



}